$(function () {
    $("#loginBtn").click(function () {
    	doLogin();
    });
    
	$("#agencyCode").bind('change', function () {
		doChangeAgency();
	});
	
	$("#changeAgencyBtn").bind('click', changeAgencyHandler);
    
	$("#loginBtn").prop("disabled", true);
	
	$.initContext(
		{
			pageCode: "partner_select", 
//			viewConfigCallback: function (selector, attrs) {
//				
//			}, 
//			pageLoadedCallback: function (viewTag) {
//				
//			}, 
			dataLoadedCallback: function (result) {
				queryLoginInfo();
			},
			ajaxStartCallback: showLoading, 
			ajaxCompleteCallback: hideLoading
		}
	);

	$("#partnerSearchButton").click(function(){
		if($("#partnerGrid").find("tbody tr").length){
			$("#partnerGrid").find("tbody tr[colspan='"+$("#partnerGridClone td").size()+"']").remove();
			$("#partnerGrid input[name='partnerCode']").prop("checked",false);

			var searchPartnerVal = $("#partnerName").val(),
				searchAgentVal = $("#agentName").length?$("#agentName").val():"",
				i = 0,
				len = $("#partnerGrid").find("tbody tr").length,
				checked = [],
				agentAuthVosArr = [],
				agentArr = [];

			for(i=0;i<len;i++){
				if($("#partnerGrid").find("tbody tr").eq(i).attr("data")){
					if(searchPartnerVal || searchAgentVal){
						if(searchPartnerVal && !searchAgentVal){
							if($("#partnerGrid tbody tr").eq(i).find("[data-label-function='renderPartnerInfo']").html().indexOf(searchPartnerVal) != -1){
								$("#partnerGrid").find("tbody tr").eq(i).show();
								if(!checked.length){
									checked.push(i);
								}
							}else{
								$("#partnerGrid").find("tbody tr").eq(i).hide();
							}
						}
						if(!searchPartnerVal && searchAgentVal){
							agentAuthVosArr = JSON.parse($("#partnerGrid tbody tr").eq(i).attr("data")).agentAuthVos;
							if(agentAuthVosArr.length){
								for(var j=0,lenj=agentAuthVosArr.length;j<lenj;j++){
									if(agentAuthVosArr[j].agentName.indexOf(searchAgentVal) != -1){
										$("#partnerGrid").find("tbody tr").eq(i).show();
										if(!checked.length){
											checked.push(i);
										}
										agentArr.push(j);
										break;
									}else{
										$("#partnerGrid").find("tbody tr").eq(i).hide();
									}
								}
							}
						}
						if(searchPartnerVal && searchAgentVal){
							agentAuthVosArr = JSON.parse($("#partnerGrid tbody tr").eq(i).attr("data")).agentAuthVos;
							if(agentAuthVosArr.length){
								for(var j=0,lenj=agentAuthVosArr.length;j<lenj;j++){
									if(agentAuthVosArr[j].agentName.indexOf(searchAgentVal) != -1 && $("#partnerGrid tbody tr").eq(i).find("[data-label-function='renderPartnerInfo']").html().indexOf(searchPartnerVal) != -1){
										$("#partnerGrid").find("tbody tr").eq(i).show();
										if(!checked.length){
											checked.push(i);
										}
										agentArr.push(j);
										break;
									}else{
										$("#partnerGrid").find("tbody tr").eq(i).hide();
									}
								}
							}
						}
					}else{
						$("#partnerGrid").find("tbody tr").eq(i).show();
						if(!checked.length){
							checked.push(i);
						}
					}
				}
			}
			$("#partnerGrid input[name='partnerCode']").eq(checked[0]).prop("checked",true);
			partnerSelected($("#partnerGrid input[name='partnerCode']").get(checked[0]));
			if(agentArr.length){
				$("#partnerGrid").find("tbody tr[colspan='"+$("#partnerGridClone td").size()+"'] [name='agentCode']").prop("checked",false);
				$("#partnerGrid").find("tbody tr[colspan='"+$("#partnerGridClone td").size()+"'] [name='agentCode']").eq(agentArr[0]).prop("checked",true);
			}
		}
	});
});

function queryLoginInfo() {
    cpic_ajax({
        url: "auth/queryFastLoginInfo",
        data: {"meta": {}, "redata": {}},
        success: function (response) {
        	var ret = response.result;

        	var curUserCode = ret.userCode;
        	var curPartnerCode = ret.partnerCode;
        	var curAgentCode = ret.agentCode;
        	var curTranSource = ret.transactionSource;

            var curIndex = 0;
        	
            createGridItems(ret.userAuthVos, $("#partnerGrid"), $("#partnerGridClone"));
            
            $.each(ret.userAuthVos, function (i, v) {
            	$("#partnerGrid tbody tr").eq(i).find("input[name='partnerCode']").val(v.partnerCode);
            	if (v.userCode == curUserCode && v.partnerCode == curPartnerCode) {
            		curIndex = i;
            	}
            });
            
            $("#partnerGrid input[name='partnerCode']").click(function (event) {
            	partnerSelected(event.target);
            });
            
            var ptrRadio = $("#partnerGrid input[name='partnerCode']").eq(curIndex);
        	$(ptrRadio).prop("checked", true);
        	
            partnerSelected(ptrRadio[0]);
            if (curAgentCode) {
            	$("#partnerGrid input[name='agentCode']").each(function (i, v) {
            		if ($(v).attr("value") == curAgentCode) {
            			$(v).prop("checked", true);
            		}
            	});
            }
            
			$("#loginBtn").prop("disabled", false);
        }
    });
}

function partnerSelected(elem) {
	var cols = $("#partnerGridClone td").size();
	
	$("#partnerGrid").find("tr[colspan='" + cols + "']").remove();
	
	if (!$(elem).prop("checked")) {
		return;
	}
	
	var partner = JSON.parse($(elem).parents("tr").attr("data"));
	if (!partner) {
		return;
	}
	
	if (partner.agencyVo) {
		$("#agencyCode").val(partner.agencyVo.agencyCode);
		$("#agencyName").text(partner.agencyVo.agencyName);
		$("#agencyName").data("agencyCode", partner.agencyVo.agencyCode);
	} else {
		$("#agencyCode").val("");
		$("#agencyName").text("");
		$("#agencyName").removeData("agencyCode");
	}
	
	if (partner.transactionSource == '23' || partner.transactionSource == '38') {
		$("#agencyCode").prop("disabled", false);
		$("#agencyReqsign").show();
		$("#changeAgencyBtn").show();
	} else {
		$("#agencyCode").prop("disabled", true);
		$("#agencyReqsign").hide();
		$("#changeAgencyBtn").hide();
	}
	
	var index = $("#partnerGrid input[name='partnerCode']").index($(elem));
	
	var ul = $("<ul style='margin: 10px 0px; overflow: hidden; line-height: 30px;' />");
	
	$.each(partner.agentAuthVos || [], function (i, v) {
		var assAgents = [];
		$.each(v.assessAgentVos || [], function (idx, item) {
			assAgents.push(item["name"] + "：" + item["assessRatio"] + "%");
		});
		
		$("<li class='col-md-12'/>")
			.append("<input type='radio' name='agentCode' id='__agent_" + i + "__' value='" + v.agentCode + "' />")
			.append("<label for='__agent_" + i + "__' style='min-width: 80px;'>" + v.agentName + "</label>")
			.append("<span style='padding-left: 20px'>" + assAgents.join("，") + "</span>")
			.appendTo($(ul));
	});
	
	var mtr = $("<tr colspan='" + cols + "' />");
	
	$("<td colspan='" + cols + "' />")
			.append($(ul))
			.appendTo($(mtr));
	
	$(mtr).insertAfter($(elem).parents("tr"));
	
	$("#partnerGrid input[name='agentCode']:eq(0)").prop("checked", true);
	
	afterPartnerSelectedHandler(partner.branchCode);
	
	if (requireMacCheck() && partner.macAddressRequired) {
		getAndCheckMacAddress();
	}
}

function changeAgencyHandler(event) {
	var agencyCode = $("#agencyCode").val();
	if (!agencyCode) {
		dialogs.warning("请输入代理点代码！", "提示");
		return;
	}
	
	doChangeAgency();
}

function doChangeAgency() {
	$("#agencyName").text("");
	$("#agencyName").removeData("agencyCode");
	
	var agencyCode = $("#agencyCode").val();
	if (!agencyCode) {
		return;
	}
	
	cpic_ajax({
		url : "queryAgencyByCode/query",
		data : {
			"meta" : {},
			"redata" : {
				"agencyCode": agencyCode
			}
		},
		success : function(response) {
			var agency = response.result || {};

			$("#agencyName").text(agency.agencyName || "");
			$("#agencyName").data("agencyCode", agency.agencyCode || "");
		}
	}, true);
}

function doLogin() {
	var partnerCheckedRadio = $("#partnerGrid input[name='partnerCode']:checked");
	
	var partnerSize = $(partnerCheckedRadio).size();
	if (partnerSize != 1) {
		dialogs.warning("请选择终端！", "提示");
		return;
	}
	
	var agentCheckedRadio = $("#partnerGrid input[name='agentCode']:checked");
	var agentSize = $(agentCheckedRadio).size();
	if (agentSize != 1) {
		dialogs.warning("请选择经办人！", "提示");
		return;
	}
	
	var partner = JSON.parse($(partnerCheckedRadio).parents("tr").attr("data"));
	
	var partnerCode = partner.partnerCode;
	var userCode = partner.userCode;
	var accessToken = partner.accessToken;
	
	var agentIndex = $("#partnerGrid input[name='agentCode']").index(agentCheckedRadio);
	var agent = partner.agentAuthVos[agentIndex];
	
	var agentCode = agent.agentCode || "";
	
	var params = {
		"access_token": accessToken, 
		"partner_code": partnerCode, 
		"j_username": userCode, 
		"agent_code": agentCode
	};
	
	if (!$("#agencyCode").prop("disabled")) {
		var agencyName = $("#agencyName").text();
		var agencyCode = $("#agencyName").data("agencyCode") || "";
		
		if (!agencyCode || !agencyName) {
			dialogs.warning("请输入正确的代理点代码！", "提示");
			return;
		}
		
		params["agency_code"] = agencyCode;
	}
	
	if (requireMacCheck() && partner.macAddressRequired) {
		var macAddr = getAndCheckMacAddress();
		if (!macAddr) {
			return;
		}
		
		params["mac_address"] = macAddr;
	}

	if(partner.cooperatorVo){
		if(partner.cooperatorVo.status && partner.cooperatorVo.status == 1){
			dialogs.warning("该终端合作伙伴已失效！", "提示");
			return;
		}
	}
	
	$("#loginBtn").attr("disabled", true);
	
	$.ajax({
		type: "POST",
		dataType: "text",
		url: "../../../../j_spring_security_check",
		data: params, 
		success : function(result) {
			var ret = JSON.parse(result);
			if (ret.authentication == "true") {
				window.top.location.href = ret.reqUri || "index.html";
			}
			else {
				var errCode = ret.errCode;
				if (errCode == "5" && requireMacCheck()) {
					dialogs.warning("当前电脑的 MAC 地址未与对应终端绑定，请联系分公司管理员处理！", "提示");
					$("#loginBtn").prop("disabled", false);
				} 
				else {
					dialogs.error("终端登录失败！", "提示", ["confirm"], function () {
						window.top.location.href = "login.html";
					});
				}
			}
		},
		error : function(xmlHttpRequest, textStatus, errorThrow) {
			$("#loginBtn").attr("disabled", false);
		},
		complete : function(XMLHttpRequest) {
			if (XMLHttpRequest.readyState < 4) {
				dialogs.error("请求超时！", "提示");
			}
		}
	});
}

function afterPartnerSelectedHandler(branchCode) {
	//noop
}
function requireMacCheck() {
	return false;
}
function getAndCheckMacAddress() {
	//noop
}

function createGridItems(dataArr, grid, tmpl) {
	grid.find("tbody").empty();
	
	for (var i = 0; dataArr && i < dataArr.length; i++) {
		var rowData = dataArr[i];
		if (!rowData) {
			continue;
		}
		
		var tr = tmpl.find("tr").show().clone();
		$(tr).attr("data", JSON.stringify(rowData));
		
		$(tr).find("td").each(function (k, v) {
			var dataField = $(v).attr("data-field");
			var labelFunc = $(v).attr("data-label-function");
			
			if (!dataField && !labelFunc) {
				return;
			}
			
			var cellVal = null;
			
			if (dataField) {
				cellVal = rowData[dataField];
			}
			
			if (labelFunc) {
				var funcStr = labelFunc + "(rowData, v)";
				cellVal = eval(funcStr);
			}
			
			if (cellVal !== null && cellVal !== undefined) {
				$(v).html(cellVal);
			}
		});
		
		grid.find("tbody").append(tr);
	}
}

function renderPartnerInfo(dataItem, cell) {
	return !dataItem ? "" : 
		(dataItem["partnerCode"] || "") + "/" + (dataItem["partnerName"] || "");
}

function renderAutoChannelInfo(dataItem, cell) {
	return !dataItem || !dataItem["autoCode"] ? ""
			: (dataItem["autoCode"] || "") + "/" + (dataItem["autoName"] || "");
}

function renderCooperatorInfo(dataItem, cell) {
	return !dataItem || !dataItem["cooperatorVo"] || !dataItem["cooperatorVo"]["cooperatorCode"] ? ""
			: (dataItem["cooperatorVo"]["cooperatorCode"] || "") + "/" + (dataItem["cooperatorVo"]["cooperatorName"] || "");
}

//对于ajax进行再次封装，显示loading
function cpic_ajax(opts,show,hide){
	var url="../../../../"+opts.url;
	$.ajax({
		type:"post",
		url: url,
		data:JSON.stringify(opts.data),
		dataType: "json",
		cache: false,
		contentType: 'application/json;charset=utf-8',
		beforeSend:function(){
			if(show)
				showLoading();
		},
		complete:function(){
			if(!hide)
				hideLoading();
		},
		success:function(response){
			if(response.message.code=='success'){
				opts.success(response);
			}else{
				dialogs.error(response.message.message,"请求出错啦！");
			}
		},error: function(xmlHttpRequest,textStatus,errorThrow){
			try {
				if (!xmlHttpRequest.status || !xmlHttpRequest.responseText) {
					return;
				}
				
				var resp = strToJson(xmlHttpRequest.responseText);
				if (resp.errCode == "99" || xmlHttpRequest.status == 401) {
					dialogs.warning("用户未登录或会话已过期，请重新登录！", errorTittle, ['confirm'], function() {
						window.location.href = '../../../../j_spring_security_logout';
					});
				}
				else {
					dialogs.warning("请求出错啦，请稍候再试！", errorTittle);
				}
			} catch(err){
				dialogs.warning("请求出错啦，请稍候再试！", errorTittle);
			}
		}
	});
}

function hideLoading(){
	$("#loading").hide();
}

function showLoading(){
	$("#loading").show();
}

var dialogs={
	error:function(content,title,buttonArr,subfunction,cancelfunction){
		$("body").append(createDialogHtml(content,title,"error",buttonArr,subfunction,cancelfunction));
	},
	warning:function(content,title,buttonArr,subfunction,cancelfunction){
		$("body").append(createDialogHtml(content,title,"warning",buttonArr,subfunction,cancelfunction));
	},
	notify:function(content,title,buttonArr,subfunction,cancelfunction){
		$("body").append(createDialogHtml(content,title,"notify",buttonArr,subfunction,cancelfunction));
	}
};

function createDialogHtml(content,title,type,buttonArr,subfunction,cancelfunction){
	var loadDiv=$("<div>").addClass("loding_bj noticeDialog");
	loadDiv.append($("<div>").addClass("float-layer"));
	var color,
		contentDiv;
	if(type == "warning"){
		contentDiv=$("<div>").addClass("float-content").css({"height":"auto" , "top":"25%" , "width":"360px" ,"left":"50%" ,"marginLeft":"-180px"});
	}else{
		contentDiv=$("<div>").addClass("float-content").css({"height":"auto" , "top":"25%" , "width":"300px" ,"left":"40%" });
	}
	switch(type){
		case "error":color="#d2322d";break;
		case "warning":color="#f0ad4e";break;
		case "notify":color="#428bca";break;
	}
	var h=$("<h4>").css("background-color", color);
	var bindSpan=$("<span>").addClass("ng-binding").html(title);
	/*var closeButton=$("<button>").addClass("close").attr("type","button").html("X");
	closeButton.click(function(){
		closeDialog();
	})*/
	h.append(bindSpan);//.append(closeButton);
	var textDiv;
	if(type == "warning"){
		textDiv=$("<div>").css({"overflow": "auto","min-height":"70px","max-height":"240px", "width":"94%","font-size":"13px","padding":"9px","padding-top":"15px"}).html(content);
	}else{
		textDiv=$("<div>").css({"overflow": "auto","min-height":"70px","max-height":"200px", "width":"94%","font-size":"14px","padding":"9px","padding-top":"15px"}).html(content);
	}
	var footDiv=$("<div>").css({"overflow": "hidden","margin-bottom":"20px"});
	var closeA=$("<a>").addClass("o-c-btn_a cursor").html("关闭");
	var subA=$("<a>").addClass("o-c-btn_a cursor").html("确认");
	var yesA=$("<a>").addClass("o-c-btn_a cursor").html("是");
	var noA=$("<a>").addClass("o-c-btn_a cursor").html("否");
	
	if(buttonArr){
		if(buttonArr[0]!=buttonArr[1]){
			addButton(buttonArr[1]);
			addButton(buttonArr[0]);
		}else{
			addButton(buttonArr[0]);
		}
	}else{
		footDiv.append(closeA);
	}
	
	noA.click(function(){
		if(cancelfunction)
			cancelfunction();
		else
			closeDialog();
	});
	
	closeA.click(function(){
		if(cancelfunction)
			cancelfunction();
		else
			closeDialog();
	});
	
	
	contentDiv.append(h).append(textDiv).append(footDiv);
	loadDiv.append(contentDiv);
	
	return loadDiv;
	
	function addButton(showButton){
		var button;
		switch(showButton){
			case "close":
				button=closeA;
				break;
			case "confirm":
				if(subfunction){
					subA.click(function(){
						subfunction();
					})
				}
				button=subA;
				break;
			case "yes":
				if(subfunction){
					yesA.click(function(){
						subfunction();
					})
				}
				button=yesA;
				break;
			case "no":
				button=noA;
				break;
		}
		footDiv.append(button);
	}
	
	
}
function closeDialog(){
	$(".noticeDialog").remove();
}